package com.permission.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.permission.dto.response.menu.PermsResponse;
import com.permission.mapper.SysMenuMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.List;

/**
 * @desc: SaToken路由拦截器配置
 * @projectName: permission-parent
 * @author: xhs
 * @date: 2023-5-27 027 17:43
 * @version: JDK 1.8
 */
@Slf4j
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
    @Resource
    private SysMenuMapper menuMapper;

    /**
     * 注册拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        log.info("======注册Sa-Token的路由拦截器======");
        // 注册Sa-Token的路由拦截器，并排除登录接口或其他可匿名访问的接口地址 (与注解拦截器无关)
        registry.addInterceptor(new SaInterceptor(handle -> StpUtil.checkLogin()))
                .addPathPatterns("/**")
                // 排除注册登录接口不需要鉴权
                .excludePathPatterns("/register")
                .excludePathPatterns("/login")
                .excludePathPatterns("/code");

        // 注册Sa-Token的路由拦截器，拦截是否有权限访问接口
        registry.addInterceptor(new SaInterceptor(handler -> {
            // 查询所有的接口地址及接口权限标识
            List<PermsResponse> permsList = menuMapper.getInterfaceInfo();
            for (PermsResponse per : permsList) {
                SaRouter.match(per.getPath(), r -> StpUtil.checkPermission(per.getPerms()));
            }
        }));
    }
}
